<template>
    <div class="show-list-container">
        <!-- 操作按钮区域 -->
        <div class="action-bar">
            <div class="left-actions">
                <el-button type="primary" icon="el-icon-plus" @click="handleAddShow">添加演出</el-button>
                <el-button type="info" icon="el-icon-refresh" @click="fetchShowList">刷新</el-button>
            </div>
            <div class="right-actions">
                <el-input v-model="searchQuery" placeholder="搜索演出名称" prefix-icon="el-icon-search" clearable
                    class="search-input" @clear="handleSearch" @keyup.enter.native="handleSearch">
                    <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
                </el-input>
            </div>
        </div>

        <!-- 演出列表表格 -->
        <el-card shadow="hover" class="table-card">
            <el-table :data="showList" border stripe style="width: 100%" v-loading="loading" class="show-table"
                :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }">
                <el-table-column prop="showId" label="演出ID" width="200" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="showName" label="演出名称" width="230" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="showType" label="演出类型" width="150" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="getTagType(scope.row.showType)">{{ scope.row.showType }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="showTime" label="演出时间" width="200" align="center" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{ scope.row.showTime }}
                    </template>
                </el-table-column>
                <el-table-column prop="showAddress" label="演出地点" width="200" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="200" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="createUser" label="创建人" width="200" align="center" show-overflow-tooltip></el-table-column>

                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button-group class="operation-btns">
                            <el-tooltip content="编辑" placement="top">
                                <el-button type="primary" size="mini" icon="el-icon-edit"
                                    @click="handleEditShow(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="查看详情" placement="top">
                                <el-button type="info" size="mini" icon="el-icon-view"
                                    @click="handleViewShow(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button type="danger" size="mini" icon="el-icon-delete"
                                    @click="handleDeleteShow(scope.row)"></el-button>
                            </el-tooltip>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页控件 -->
            <div class="pagination-container">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]"
                    :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" background></el-pagination>
            </div>
        </el-card>

        <!-- 添加/编辑演出对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" @close="resetForm" center>
            <el-form :model="showForm" :rules="rules" ref="showForm" label-width="100px" status-icon>
                <el-form-item label="演出名称" prop="showName">
                    <el-input v-model="showForm.showName" placeholder="请输入演出名称"></el-input>
                </el-form-item>
                <el-form-item label="剧种类型" prop="showType">
                    <el-select v-model="showForm.showType" placeholder="请选择剧种类型" style="width: 100%">
                        <el-option label="公益" value="公益"></el-option>
                        <el-option label="商业" value="商业"></el-option>
                        <el-option label="文化交流" value="文化交流"></el-option>
                        <el-option label="其他" value="其他"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="演出时间" prop="showTime">
                    <el-date-picker v-model="showForm.showTime" type="datetime" placeholder="选择演出时间"
                        style="width: 100%"></el-date-picker>
                </el-form-item>
                <el-form-item label="演出地点" prop="showAddress">
                    <el-input v-model="showForm.showAddress" placeholder="请输入演出地点"></el-input>
                </el-form-item>
                <el-form-item label="演出海报" prop="posterUrl">
                    <el-upload class="poster-uploader" action="http://localhost:9002/api/system/image/imageshow"
                        :show-file-list="false" :on-success="handlePosterSuccess" :before-upload="beforePosterUpload">
                        <img v-if="showForm.posterUrl" :src="showForm.posterUrl" class="poster-image">
                        <i v-else class="el-icon-plus poster-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="演出简介" prop="description">
                    <el-input type="textarea" v-model="showForm.description" rows="4" placeholder="请输入演出简介"></el-input>
                </el-form-item>
                <!-- <el-form-item label="节目单" prop="programs">
                    <div class="program-list">
                        <div v-for="(program, index) in showForm.programs" :key="index" class="program-item">
                            <el-row :gutter="10">
                                <el-col :span="7">
                                    <el-input v-model="program.name" placeholder="节目名称"></el-input>
                                </el-col>
                                <el-col :span="5">
                                    <el-input v-model="program.performer" placeholder="表演者"></el-input>
                                </el-col>
                                <el-col :span="4">
                                    <el-input v-model="program.duration" placeholder="时长(分钟)"></el-input>
                                </el-col>
                                <el-col :span="6">
                                    <el-input v-model="program.description" placeholder="简介"></el-input>
                                </el-col>
                                <el-col :span="2">
                                    <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="removeProgram(index)"></el-button>
                                </el-col>
                            </el-row>
                        </div>
                        <div class="add-program-btn">
                            <el-button type="primary" size="small" icon="el-icon-plus" @click="addProgram">添加节目</el-button>
                        </div>
                    </div>
                </el-form-item> -->
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 演出详情对话框 -->
        <el-dialog title="演出详情" :visible.sync="detailsVisible" width="800px" center>
            <el-row :gutter="20">
                <el-col :span="8">
                    <div class="show-poster">
                        <img :src="currentShow.posterUrl" alt="演出海报">
                    </div>
                </el-col>
                <el-col :span="16">
                    <el-descriptions class="show-details" :column="1" border>
                        <el-descriptions-item label="演出名称">{{ currentShow.showName }}</el-descriptions-item>
                        <el-descriptions-item label="演出类型">
                            <el-tag type="primary">{{ currentShow.showType }}</el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="演出时间">{{ currentShow.showTime }}</el-descriptions-item>
                        <el-descriptions-item label="演出地点">{{ currentShow.showAddress }}</el-descriptions-item>
                        <el-descriptions-item label="演出简介">
                            <div class="show-description">{{ currentShow.description }}</div>
                        </el-descriptions-item>
                    </el-descriptions>
                </el-col>
            </el-row>
            
            <!-- 添加节目单显示部分
            <div class="program-section">
                <h3>节目单</h3>
                <el-table :data="currentShow.programs || []" stripe style="width: 100%">
                    <el-table-column prop="name" label="节目名称" width="180"></el-table-column>
                    <el-table-column prop="performer" label="表演者" width="120"></el-table-column>
                    <el-table-column prop="duration" label="时长(分钟)" width="100"></el-table-column>
                    <el-table-column prop="description" label="简介"></el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                        <template slot-scope="scope">
                            <el-button type="primary" size="mini" icon="el-icon-edit" @click="editProgram(scope.row, scope.$index)"></el-button>
                            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteProgram(scope.$index)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div> -->
            
            <span slot="footer" class="dialog-footer">
                <el-button @click="detailsVisible = false">关 闭</el-button>
            </span>
        </el-dialog>
        
        <!-- 编辑节目对话框
        <el-dialog title="编辑节目" :visible.sync="programDialogVisible" width="500px" center>
            <el-form :model="programForm" label-width="100px">
                <el-form-item label="节目名称" prop="name">
                    <el-input v-model="programForm.name" placeholder="请输入节目名称"></el-input>
                </el-form-item>
                <el-form-item label="表演者" prop="performer">
                    <el-input v-model="programForm.performer" placeholder="请输入表演者姓名"></el-input>
                </el-form-item>
                <el-form-item label="时长(分钟)" prop="duration">
                    <el-input v-model="programForm.duration" placeholder="请输入时长"></el-input>
                </el-form-item>
                <el-form-item label="简介" prop="description">
                    <el-input type="textarea" v-model="programForm.description" rows="3" placeholder="请输入简介"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="programDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveProgramEdit">确 定</el-button>
            </span>
        </el-dialog> -->
    </div>
</template>

<script>
import service from '@/utils/request';

export default {
    name: 'ShowList',
    data() {
        return {
            // 演出列表数据
            showList: [],
            loading: false,
            searchQuery: '',

            // 分页参数
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            },

            // 对话框控制
            dialogVisible: false,
            detailsVisible: false,
            dialogTitle: '添加演出',
            isAddMode: true,
            programDialogVisible: false,

            // 当前编辑/查看的演出
            currentShow: {},
            
            // // 当前编辑的节目
            // programForm: {
            //     name: '',
            //     performer: '',
            //     duration: '',
            //     description: ''
            // },
            // currentProgramIndex: -1,

            // 表单数据
            showForm: {
                showId: '',
                showName: '',
                showType: '公益',
                showTime: '',
                showAddress: '',
                posterUrl: '',
                description: '',
                // programs: [], // 节目单列表
                token: localStorage.getItem('token')
            },

            // 表单验证规则
            rules: {
                showName: [
                    { required: true, message: '请输入演出名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                showType: [
                    { required: true, message: '请选择演出类型', trigger: 'change' }
                ],
                showTime: [
                    { required: true, message: '请选择演出时间', trigger: 'change' }
                ],
                showAddress: [
                    { required: true, message: '请输入演出地点', trigger: 'blur' }
                ],
                description: [
                    { required: true, message: '请输入演出简介', trigger: 'blur' },
                    { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
                ]
            }
        };
    },
    created() {
        this.fetchShowList();
        window.scrollTo(0, 0);
    },
    methods: {
        // 获取演出列表
        fetchShowList() {
            this.loading = true;
            service.get('/api/content/show/getShowList', {
                params: {
                    pageNum: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize,
                    showName: this.searchQuery
                }
            }).then(res => {
                if (res.code === 200) {
                    this.showList = res.data.list;
                    this.pagination.total = res.data.total;
                    // this.$message({
                    //     type: 'success',
                    //     message: '获取演出列表成功!'
                    // });
                }
            }).catch(err => {
                this.$message.error(err.message);
            }).finally(() => {
                this.loading = false;
            });
        },

        // 处理搜索
        handleSearch() {
            this.pagination.currentPage = 1;
            this.fetchShowList();
        },

        // 处理分页大小变化
        handleSizeChange(val) {
            this.pagination.pageSize = val;
            this.fetchShowList();
        },

        // 处理当前页变化
        handleCurrentChange(val) {
            this.pagination.currentPage = val;
            this.fetchShowList();
        },

        // 处理添加演出
        handleAddShow() {
            this.isAddMode = true;
            this.dialogTitle = '添加演出';
            this.resetForm();
            this.dialogVisible = true;
        },

        // 处理编辑演出
        handleEditShow(row) {
            this.isAddMode = false;
            this.dialogTitle = '编辑演出';
            this.showForm = JSON.parse(JSON.stringify(row));
            // // 确保programs字段存在
            // if(!this.showForm.programs) {
            //     this.showForm.programs = [];
            // }
            this.showForm.token = localStorage.getItem('token');
            this.dialogVisible = true;
        },

        // 处理查看演出详情
        handleViewShow(row) {
            this.currentShow = row;
            this.detailsVisible = true;
            // service.get(`/api/content/show/getShowDetail/${row.showId}`).then(res => {
            //     if(res.code === 200) {
            //         this.currentShow = res.data;
            //         // 确保programs字段存在
            //         if(!this.currentShow.programs) {
            //             this.currentShow.programs = [];
            //         }
            //     }
            // }).catch(err => {
            //     this.$message.error(err.message);
            // });
        },

        // 处理删除演出
        handleDeleteShow(row) {
            this.$confirm('确认删除该演出信息吗?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    service.delete(`/api/content/show/deleteShow/${row.showId}`).then(res => {
                        if (res.code === 200) {
                            this.$message.success('删除成功');
                            this.fetchShowList();
                        }
                    }).catch(err => {
                        this.$message.error(err.message);
                    })
                })
                .catch(() => {
                    this.$message.info('已取消删除');
                });
        },

        // 重置表单
        resetForm() {
            if (this.$refs.showForm) {
                this.$refs.showForm.resetFields();
            }
            this.showForm = {
                showId: '',
                showName: '',
                showType: '公益',
                showTime: '',
                showAddress: '',
                posterUrl: '',
                description: '',
                // programs: [], // 重置节目单
                token: localStorage.getItem('token')
            };
        },

        // 提交表单
        submitForm() {
            this.$refs.showForm.validate(valid => {
                if (valid) {
                    // 格式化 showTime
                    if (this.showForm.showTime) {
                        const date = new Date(this.showForm.showTime);
                        this.showForm.showTime = date.toISOString().slice(0, 19).replace('T', ' '); // 转换为 'YYYY-MM-DD HH:mm:ss' 格式
                    }

                    const request = this.isAddMode ? service.post('/api/content/show/addShow', this.showForm) : service.put('/api/content/show/updateShow', this.showForm)
                    request.
                        then(res => {
                            if (res.code === 200) {
                                this.$message.success(this.isAddMode ? '添加成功' : '更新成功');
                                this.dialogVisible = false;
                                this.fetchShowList();
                            }
                        }).catch(err => {
                            this.$message.error(err.message);
                        });
                }
            });
        },

        // 处理海报上传成功
        handlePosterSuccess(res, file) {

            if (res.code === 200) {
                this.showForm.posterUrl = res.data;
                console.log('上传的文件名:', file.name);
            } else {
                this.$message.error('上传失败');
            }
        },

        // 海报上传前的验证
        beforePosterUpload(file) {
            const isImage = file.type.startsWith('image/');
            const isLt4M = file.size / 1024 / 1024 < 4;

            if (!isImage) {
                this.$message.error('上传的文件必须是图片!');
            }
            if (!isLt4M) {
                this.$message.error('上传的图片大小不能超过 4MB!');
            }

            return isImage && isLt4M;
        },

        // 处理取消操作
        handleCancel() {

            // // 添加逻辑以删除已上传的图片
            // if (this.showForm.posterUrl) {
            //     service.delete(`/api/system/image/deleteImageshow/${this.showForm.posterUrl}`).then(res => {
            //         if (res.code === 200) {
            //             this.resetForm(); // 重置表单
            //         }
            //     })
            // }
            // 添加逻辑以删除已上传的图片
            if (this.showForm.posterUrl) {
                service.delete('/api/system/image/deleteImageshow', {
                    params: {
                        url: this.showForm.posterUrl
                    }
                }

                ).then(res => {
                    if (res.code === 200) {
                        this.resetForm(); // 重置表单
                    }
                })
            }
            this.dialogVisible = false; // 关闭对话框
        },

        // // 添加节目
        // addProgram() {
        //     this.showForm.programs.push({
        //         name: '',
        //         performer: '',
        //         duration: '',
        //         description: ''
        //     });
        // },
        
        // // 移除节目（在编辑表单中）
        // removeProgram(index) {
        //     this.showForm.programs.splice(index, 1);
        // },
        
        // // 编辑节目（在详情页中）
        // editProgram(program, index) {
        //     this.programForm = JSON.parse(JSON.stringify(program));
        //     this.currentProgramIndex = index;
        //     this.programDialogVisible = true;
        // },
        
        // // 保存节目编辑
        // saveProgramEdit() {
        //     if(this.currentProgramIndex !== -1) {
        //         // 更新节目信息
        //         this.$set(this.currentShow.programs, this.currentProgramIndex, this.programForm);
                
        //         // 保存到服务器
        //         service.put(`/api/content/show/updateProgram/${this.currentShow.showId}`, {
        //             programIndex: this.currentProgramIndex,
        //             program: this.programForm,
        //             token: localStorage.getItem('token')
        //         }).then(res => {
        //             if(res.code === 200) {
        //                 this.$message.success('节目更新成功');
        //                 this.programDialogVisible = false;
        //             }
        //         }).catch(err => {
        //             this.$message.error(err.message);
        //         });
        //     }
        // },
        
        // // 删除节目（在详情页中）
        // deleteProgram(index) {
        //     this.$confirm('确认删除该节目?', '警告', {
        //         confirmButtonText: '确定',
        //         cancelButtonText: '取消',
        //         type: 'warning'
        //     }).then(() => {
        //         // 从列表中移除
        //         this.currentShow.programs.splice(index, 1);
                
        //         // 保存到服务器
        //         service.delete(`/api/content/show/deleteProgram/${this.currentShow.showId}/${index}`, {
        //             params: {
        //                 token: localStorage.getItem('token')
        //             }
        //         }).then(res => {
        //             if(res.code === 200) {
        //                 this.$message.success('节目删除成功');
        //             }
        //         }).catch(err => {
        //             this.$message.error(err.message);
        //         });
        //     }).catch(() => {
        //         this.$message.info('已取消删除');
        //     });
        // },

        getTagType(showType) {
            switch (showType) {
                case '公益':
                    return 'success'; // 绿色
                case '商业':
                    return 'warning'; // 橙色
                case '文化交流':
                    return 'Brand Color'; // 蓝色
                case '其他':
                    return 'danger'; // 红色
                default:
                    return ''; // 默认颜色
            }
        }
    }
};
</script>

<style scoped>
.show-list-container {
    padding: 20px;
}

.action-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
}

.table-card {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

.poster-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    display: block;
}

.poster-uploader:hover {
    border-color: #409EFF;
}

.poster-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.poster-image {
    width: 178px;
    height: 178px;
    display: block;
}

.show-poster img {
    width: 100%;
    border-radius: 4px;
}

.show-description {
    white-space: pre-line;
    line-height: 1.5;
}

.program-list {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 10px;
    background-color: #f8f8f8;
}

.program-item {
    margin-bottom: 10px;
    padding: 10px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.add-program-btn {
    margin-top: 10px;
    text-align: center;
}

.program-section {
    margin-top: 20px;
    padding: 15px;
    border-top: 1px solid #ebeef5;
    /* border-top: 1px solid #1d47aa; */
}

.program-section h3 {
    margin-bottom: 15px;
    font-weight: 500;
    color: #303133;
}
</style>
